package org.eclipse.pde.toolbox.internal;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.eclipse.core.internal.registry.ExtensionPoint;
import org.eclipse.core.runtime.IContributor;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Platform;

public class ContributorRoot implements IRoot {

	private ContributorNode[] contributorNodes = null;
	public static final ContributorRoot instance = new ContributorRoot();

	@Override
	public ITreeNode[] getChildren() {
		// TODO Auto-generated method stub
		if (contributorNodes == null) {

			IExtensionRegistry extensionRegistry = Platform
					.getExtensionRegistry();
			IExtensionPoint[] extensionPointList = extensionRegistry
					.getExtensionPoints();
			Map extensionsMap = new HashMap();

			for (int i = 0; i < extensionPointList.length; i++) {
				if (extensionPointList[i].getUniqueIdentifier()
						.equalsIgnoreCase("org.eclipse.core.runtime.adapters")) {
					IExtension[] extensions = extensionPointList[i]
							.getExtensions();
					for (int j = 0; j < extensions.length; j++) {

						IContributor contributor = extensions[j]
								.getContributor();
						Set contributorsExtensions = (Set) extensionsMap
								.get(contributor);
						if (contributorsExtensions == null) {
							contributorsExtensions = new HashSet();
							extensionsMap.put(contributor,
									contributorsExtensions);
						}
						contributorsExtensions.add(extensions[j]);
					}
				}
			}

			Set entries = extensionsMap.entrySet();
			contributorNodes = new ContributorNode[entries.size()];
			int k = 0;
			for (Iterator i = entries.iterator(); i.hasNext();) {
				Map.Entry entry = (Map.Entry) i.next();
				contributorNodes[k] = new ContributorNode((IContributor) entry
						.getKey(), (Set) entry.getValue());
				k++;
			}
		}

		return contributorNodes;
	}

	@Override
	public boolean isTopLevelElement(Object element) {
		// TODO Auto-generated method stub
		return element instanceof ContributorNode;
	}

}
